import type { SearchConfigValue } from "./table-configtypes";
import { OperatorTypeEnums, ConditionsTypeEnums } from "./wrapper-enums";
import type { QueryCondition, QueryOrder, QueryPage, QueryWrapper } from "./wrappertypes";

/**
 * 根据selector 结构 返回对应conditions
 * @param param
 * @returns {QueryWrapper} 返回构建的查询包装器
 */
export const buildQueryCondition = (param: Array<SearchConfigValue>): QueryCondition[] => {
  if (!param || param.length === 0) {
    return [{}] as QueryCondition[];
  }
  const res : QueryCondition[] = [];
  //根据类型转换Condition对象 ***！重点
  param.forEach(i => {
    const r:QueryCondition =  typeHandler(i);
    if(r.field && r.value){
      res.push(typeHandler(i));
    }
  })
  console.log("构造selecotr后的condition结果:",res)
  return res;
}

/**
 * 构造wrapper
 * @param conditions
 * @param page
 * @param order
 * @returns
 */
export const buildQueryWrapper= (conditions:Array<QueryCondition> , page:QueryPage , order:QueryOrder[]) : QueryWrapper =>{
  if(!conditions){
    return {} as QueryWrapper;
  }
  const res: QueryWrapper = {
    condition : conditions,
    page:page,
    sort:order,
  };
  return res;
}





//类型处理
const typeHandler = (configvalue: SearchConfigValue): QueryCondition => {
  //字符串类型处理
  switch (configvalue.fieldType) {
    case 'String':
      return StringTypeHanlde(configvalue);
    //todo 其他类型待新增，我先把流程写好
  }
  return {} as QueryCondition;
}



//string类型处理
const StringTypeHanlde = (configvalue: SearchConfigValue): QueryCondition => {
  //默认构造
  const condition: QueryCondition = {
    field: camelToSnake(configvalue.field as string) || '', //小写转驼峰 feild属性名 没有的话 为空  与数据库保持一致，后端暂时不做处理。
    operator: configvalue.operateType || OperatorTypeEnums.WRAPPER_CONDITION_TYPE_EQ, //默认按eq逻辑构造condition
    valueType: ConditionsTypeEnums.WRAPPER_CONDITION_TYPE_STRING,
    value:configvalue.pass_data || [],
  };
  return condition; // 返回构建好的 QueryCondition
}








function camelToSnake(camelCaseString : string) {
  if(! camelCaseString){
    return ''
  }
  return camelCaseString.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
}

